﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QueuesData {
    public class QueuesDataAdapter {
        public IEnumerable<QueuesLib.Subject> Subjects {
            get {
                using (var db = new QueuesDBEntities()) {
                    foreach (var a in db.CurrentSubjects) {
                        yield return new QueuesLib.Subject(a.Id, a.Name, a.Mnemonic);
                    }
                    yield break;
                }
            }
        }


        public IEnumerable<QueuesLib.Counter> Counters {
            get {
                using (var db = new QueuesDBEntities()) {
                    foreach (var c in db.Counters) {
                        var cont = new QueuesLib.Counter();
                        cont.SubjectId = c.SubjectId;
                        cont.Count = (c.Count ?? 0);
                        cont.EarliestTicketCreationTime = c.EarliestTicketCreationTime;
                        yield return cont;
                    }
                    yield break;
                }
            }
        }

        public IEnumerable<QueuesLib.QueueInfo> QueuesCurrentState {
            get {
                using (var db = new QueuesDBEntities()) {
                    foreach (var a in db.CurrentSubjects) {
                        var info = new QueuesLib.QueueInfo();
                        info.SubjectId = a.Id;
                        info.SubjectName = a.Name;
                        var curr = from c in db.CurrentTickets
                                   where c.SubjectId == a.Id
                                   orderby c.StartTime descending
                                   select c;
                        if (curr.Count() == 0) {
                            info.WorkStationName = "";
                            info.TicketText = "";
                        } else {
                            info.WorkStationName = curr.First().WorkStationName;
                            info.TicketText = curr.First().TicketText;
                        }
                        yield return info;
                    }
                    yield break;
                }
            }
        }

        public IEnumerable<QueuesLib.QueueInfo> TicketsBeingAttended {
            get {
                using (var db = new QueuesDBEntities()) {
                    foreach (var s in db.CurrentTickets) {
                        var i = new QueuesLib.QueueInfo();
                        i.SubjectName = s.SubjectName;
                        i.WorkStationName = s.WorkStationName;
                        i.TicketText = s.TicketText;
                        yield return i;
                    }
                    yield break;
                }
            }
        }
    }
}
